<template>
	<text>
		<text v-if="false" class="pub-chat" @click="createChatHandle">讨论组<text v-if="unreadNum">{{unreadNum}}</text></text>
		<thDialog title="发起讨论" v-model:visible="visible" align="bottom">
			<template v-slot:content>
				<view class="form">
					<view class="row" v-if="aboutList.length">
						<view class="title">相关讨论组</view>
						<view class="chatnames">
							<view class="name" v-for="item in aboutList" :key="item.id" @click="openThis(item)">
								<text v-if="item.unreadNum" style="color:red">({{item.unreadNum}})</text>{{item.chatName}}
							</view>
						</view>
					</view>
					<!-- <view class="row">
						<view class="title">模块</view>
						<th-input border v-model:value="paramsData.modules" disabled placeholder="模块"
							style="padding: 10rpx 0"></th-input>
					</view> -->
					<view class="row">
						<view class="title">讨论组名称</view>
						<th-input border v-model:value="paramsData.chatName" placeholder="讨论组名称" clearable
							height="300rpx" style="padding: 10rpx 0"></th-input>
					</view>
					<view class="row">
						<view class="title">备注</view>
						<th-input border v-model:value="paramsData.remark" placeholder="备注" clearable height="300rpx"
							style="padding: 10rpx 0"></th-input>
					</view>
					<view class="row">
						<view class="title">讨论人员</view>
						<view class="group-user">
							<template v-for="user in paramsData.baseUserList" :key="user.value">
								<thCheckbox v-model="user.checked" class="checkbox">
									<template v-slot:label>{{user.label}}</template>
								</thCheckbox>
							</template>
						</view>
					</view>
				</view>
			</template>
			<template v-slot:footer>
				<view style="text-align: right;padding:30rpx">
					<thButton @click="cancelHandle">取消</thButton>
					<thButton type="primary" :loading="pubLoading" @click="pubChatHandle" style="margin-left:15rpx;">提交
					</thButton>
				</view>
			</template>
		</thDialog>
	</text>
</template>

<script setup lang="ts">
	import { createChat, getByBusinessId, getUserList } from '@/service/chat'
	import thDialog from '@/pages/pm/assay-report/component/th-dialog.vue';
	import thInput from '@/pages/pm/assay-report/component/th-input.vue';
	import thButton from '@/pages/pm/assay-report/component/th-button.vue';
	import thCheckbox from './th-checkbox.vue'
	import showModal from '@/utils/modal';

	const props = defineProps({
		params: {
			type: Object,
			default: () => {
				return {}
			}
		}
	});

	const emits = defineEmits(['onCreateChatHandle'])
	const key = ref(new Date().getTime());

	/**
		 * @relationId
		 * @chatName
		 * @remark
		 * @relationType
		 * @modules
		 * @relationUrl
		 * @appRelationUrl
	**/
	const paramsData = ref({
		chatName: '',
		remark: '',
		relationType: '',
		modules: '',
		relationId: '',
		relationUrl: '',
		userList: [],
		baseUserList: [],
		defaultChecked: [],
		baseUsers: [],
		userApi: ''
	});

	const unreadNum = ref(0);
	watch([() => props.params, key], (n) => {
		let baseUsers = [];
		const [n1, n2] = n;
		paramsData.value = { ...n1 };
		// 获取相关讨论组
		if (paramsData.value.relationId) {
			getByBusinessId(paramsData.value.relationId).then((res) => {
				if (res.code === 0) {
					aboutList.value = res.data;

					unreadNum.value = res.data
						.filter((chat) => chat.unreadNum)
						.map((chat) => chat.unreadNum)
						.reduce((acc, curr) => acc + curr, 0);
				}
			});
		};
		// 获取默认人员
		if (paramsData.value.userApi) {
			getUserList(paramsData.value.userApi).then((res) => {
				if (res.code === 0) {
					paramsData.value.baseUserList = res.data.map((res) => {
						return {
							label: res.username,
							value: res.usercode,
							checked: true
						};
					});
				}
			});
		} else {
			if (n1.defaultChecked.length) {
				const baseUsers = n1.baseUserList.map(user => {
					if (n1.defaultChecked.includes(user.value)) {
						user.checked = true
					} else {
						user.checked = false
					}
					return { ...user };
				})


				paramsData.value.baseUserList = baseUsers.map((item) => {
					return {
						label: item.username,
						value: item.usercode,
						checked: item.checked
					};
				})
			}
		}

	}, {
		immediate: true,
		deep: true
	})


	const visible = ref(false);
	const createChatHandle = () => {
		visible.value = true;
		// createChat(props.params).then((res) => {
		// 	if (res.code === 0) {
		// 		uni.navigateTo({
		// 			url: '/pages/chat/list'
		// 		})
		// 	}
		// });
	};
	const cancelHandle = () => {
		visible.value = false;
		key.value = new Date().getTime();
	}

	const pubLoading = ref(false);
	const pubChatHandle = () => {
		if (pubLoading.value) true;
		// const checkedList = paramsData.value.baseUsers.filter(user => user.checked).map(user => user.value);
		// if (!checkedList.length) {
		// 	uni.showToast({
		// 		title: "请选择人员",
		// 		icon: "none"
		// 	})
		// 	return false;
		// }
		if (!paramsData.value.chatName) {
			uni.showToast({
				title: "讨论组名称不能为空",
				icon: "none"
			})
			return false;
		}
		if(aboutList.value.length){
			showModal({
				title: '提示',
				content: '已存在相关讨论组，是否要再次发起？',
				showCancel: true,
				confirm: () => {
					pubLoading.value = true;
					paramsData.value.userList = paramsData.value.baseUserList.filter(user => user.checked).map(user => {
						return {
							userCode: user.value,
							userName: user.label
						}
					});
					createChat(paramsData.value)
						.then((res) => {
							if (res.code === 0) {
								visible.value = false;
								uni.navigateTo({
									url: `/pages/chat/index?chatId=${res.data}`
								})
							}
						}).catch(err => {
							uni.showToast({
								title: "提交失败,请重试",
								icon: "none"
							})
						})
						.finally(() => {
							pubLoading.value = false;
						});
				},
			});
		}else{
			pubLoading.value = true;
			paramsData.value.userList = paramsData.value.baseUserList.filter(user => user.checked).map(user => {
				return {
					userCode: user.value,
					userName: user.label
				}
			});
			createChat(paramsData.value)
				.then((res) => {
					if (res.code === 0) {
						visible.value = false;
						uni.navigateTo({
							url: `/pages/chat/index?chatId=${res.data}`
						})
					}
				}).catch(err => {
					uni.showToast({
						title: "提交失败,请重试",
						icon: "none"
					})
				})
				.finally(() => {
					pubLoading.value = false;
				});
		}
	}

	const aboutList = ref([]);
	watch(visible, (n) => {
		if (n) {
			getByBusinessId(paramsData.value.relationId).then((res) => {
				if (res.code === 0) {
					aboutList.value = res.data;
				}
			});
		}
		emits('onCreateChatHandle',visible.value)
	});

	const openThis = (item) => {
		visible.value = false;
		uni.navigateTo({
			url: `/pages/chat/index?chatId=${item.id}`
		})
	};
</script>

<style lang="scss" scoped>
	.pub-chat {
		color: #007aff !important;
		position: relative;
		text{
			position: absolute;
			top:-12rpx;
			right:-5rpx;
			color:red!important;
			border-radius:5rpx;
			font-size:20rpx;
		}
	}

	.form {
		padding: 15rpx;

		.row {
			margin-top: 15rpx;

			.title {
				margin-bottom: 10rpx;
				color: #333;
			}
		}

		.chatnames {
			max-height: 200rpx;
			overflow-y: auto;
			border: 1px solid #dcdfe6;
			border-radius: 8rpx;
			padding: 5rpx 0;

			.name {
				color: #007aff;
				margin: 0 20rpx;
				line-height: 45rpx;
				white-space: nowrap;
			}
		}
	}

	.group-user {
		border: 1px solid #dcdfe6;
		border-radius: 8rpx;
		padding: 10rpx;
		margin-top: 20rpx;
		max-height: 300rpx;
		overflow-y: scroll;

		.checkbox {
			margin: 5rpx 20rpx 5rpx 0;
		}
	}
</style>